package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wlhse.dao.*;
import com.wlhse.dto.*;
import com.wlhse.dto.inDto.HseAuditGroupMemberDtos;
import com.wlhse.dto.inDto.HseAuditGroupMembersDtos;
import com.wlhse.dto.inDto.QHSEECheckRecords;
import com.wlhse.dto.inDto.QHseeCheckRecordDto;
import com.wlhse.dto.outDto.QHSEECheckRecordNumsDto;
import com.wlhse.dto.outDto.QHSEECompanyDto;
import com.wlhse.dto.outDto.QhseeSystemDto;
import com.wlhse.entity.HseAuditTaskPojo;
import com.wlhse.entity.QHSEECheckRecordPojo;
import com.wlhse.service.HSEService;
import com.wlhse.util.GetCurrentUserIdUtil;
import com.wlhse.util.R;
import com.wlhse.util.TreeUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class HSEServiceImpl implements HSEService {

    @Resource
    private HSEDao hseDao;
    @Resource
    private CompanyDao companyDao;
    @Resource
    private TaskAddDao taskAddDao;
    @Resource
    private GetCurrentUserIdUtil getCurrentUserIdUtil;
    @Resource
    private TreeUtil treeUtil;

    @Override
    @Transactional
    public String addHSEAuditGroup(HSEAuditGroupDto hseAuditGroupDto) {
        //新增检查组
        String codeStr = hseAuditGroupDto.getCompanyName();
        String[] codes = codeStr.split(",");
        StringBuilder companyCode=new StringBuilder();
        for (String code : codes) {
            companyCode.append(companyDao.queryByCompanyName(code)).append(",");
        }
        companyCode.deleteCharAt(companyCode.length()-1);
        hseAuditGroupDto.setCompanyCode(companyCode.toString());

        int count = hseDao.addHSEAuditGroup(hseAuditGroupDto);
        int auditGroupID = hseAuditGroupDto.getAuditGroupID();
        if(count<1){
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.INSERT_FAILE,null,null,0,0);
        }
        //新增检查组组员
        List<HseAuditGroupMemberDtos> members = hseAuditGroupDto.getMembers();
        if(members!=null&&members.size()>0){
            for (HseAuditGroupMemberDtos member : members) {
                member.setAuditGroupID(auditGroupID);
                hseDao.addHseAuditGroupMembers(member);
            }
        }
        return NR.r();
    }

    @Override
    public String queryHSEAuditGroup(HSEAuditGroupDto hseAuditGroupDto) {
        List<HSEAuditGroupDto> groups = hseDao.queryHSEAuditGroup(hseAuditGroupDto);
        return NR.r(groups);
    }

    @Override
    public String deleteHSEAuditGroup(Integer id) {
        hseDao.deleteHSEAuditGroup(id);
        hseDao.deleteHSEAuditGroupMember(id);
        return NR.r();
    }

    @Override
    public String queryAllGroupMembersByYearRound(HSEAuditGroupDto hseAuditGroupDto, HttpServletRequest request) {
        Integer userid=getCurrentUserIdUtil.getUserId(request);
        hseAuditGroupDto.setUserID(userid);

        List<HseAuditGroupMemberDto> members = hseDao.queryAllGroupMembersByYearRound(hseAuditGroupDto);

        //只要当前登录人为组长的值
        List<HseAuditGroupMemberDto> res=new LinkedList<>();
        List<String> auditGroupIDs = hseDao.getAuditGroupIDByUserID(userid);
        for (String id:auditGroupIDs) {
            for (HseAuditGroupMemberDto member : members) {
                if(member.getAuditGroupID().equals(id)){
                    res.add(member);
                }
            }
        }

        HashMap<String, List<HseAuditGroupMemberDto>> map = new HashMap<>();
        for (HseAuditGroupMemberDto member : res) {
            if(!map.containsKey(member.getAuditGroupID())){
                LinkedList<HseAuditGroupMemberDto> list = new LinkedList<>();
                list.add(member);
                map.put(member.getAuditGroupID(),list);
            }else{
                List<HseAuditGroupMemberDto> list = map.get(member.getAuditGroupID());
                list.add(member);
                map.put(member.getAuditGroupID(),list);
            }
        }
        return NR.r(map);
    }

    @Override
    public String addHseAuditTask(HseAuditTaskPojo hseAuditTaskPojo, HttpServletRequest request) {
        //获取当前登陆人（任务执行人）的name及id
        Integer userid = getCurrentUserIdUtil.getUserId(request);
        String uname = taskAddDao.queryEmployeeName(userid).getName();

        //先判断是否已存在taskname\round\taskdate都相等的任务
        System.out.println(hseDao.queryHseAuditTaskByTasknameRoundTaskdate(hseAuditTaskPojo));
        if(hseDao.queryHseAuditTaskByTasknameRoundTaskdate(hseAuditTaskPojo)!=null){
            return NR.r(CodeDict.INSERT_FAILE,"新增任务失败，任务名称，监督轮次和任务时间均重复");
        }

        hseAuditTaskPojo.setTaskStaffID(userid);
        hseAuditTaskPojo.setTaskStaffName(uname);
        hseAuditTaskPojo.setStatus("进行中");

        int count =hseDao.addHseAuditTask(hseAuditTaskPojo);
        if(count<1){
            return NR.r(CodeDict.INSERT_FAILE,"新增任务失败，请重试");
        }
        return NR.r();
    }

    @Override
    public String queryHseAuditTask(String taskDate,String round,Integer num,Integer size) {
        HseAuditTaskPojo hseAuditTaskPojo=new HseAuditTaskPojo();
        hseAuditTaskPojo.setRound(round);
        hseAuditTaskPojo.setTaskDate(taskDate);
        //根据是否传入taskDate和round来模糊查询
        if (hseAuditTaskPojo.getRound().equals("") && hseAuditTaskPojo.getTaskDate().equals("")){
            int total = hseDao.queryHseAuditTask1(hseAuditTaskPojo).size();
            PageHelper.startPage(num,size);
            List<HseAuditTaskPojo> tasks = hseDao.queryHseAuditTask1(hseAuditTaskPojo);
            return NR.r(tasks,total,num);
        }else if (!hseAuditTaskPojo.getRound().equals("") && hseAuditTaskPojo.getTaskDate().equals("")){
            int total = hseDao.queryHseAuditTask2(hseAuditTaskPojo).size();
            PageHelper.startPage(num,size);
            List<HseAuditTaskPojo> tasks = hseDao.queryHseAuditTask2(hseAuditTaskPojo);
            return NR.r(tasks,total,num);
        }else if(hseAuditTaskPojo.getRound().equals("") && !hseAuditTaskPojo.getTaskDate().equals("")){
            int total = hseDao.queryHseAuditTask3(hseAuditTaskPojo).size();
            PageHelper.startPage(num,size);
            List<HseAuditTaskPojo> tasks = hseDao.queryHseAuditTask3(hseAuditTaskPojo);
            return NR.r(tasks,total,num);
        }else {
            int total = hseDao.queryHseAuditTask4(hseAuditTaskPojo).size();
            PageHelper.startPage(num,size);
            List<HseAuditTaskPojo> tasks = hseDao.queryHseAuditTask4(hseAuditTaskPojo);
            return NR.r(tasks,total,num);
        }
    }


    @Override
    public String finishHseAuditTask(HseAuditTaskPojo hseAuditTaskPojo) {
        int count = hseDao.finishHseAuditTask(hseAuditTaskPojo.getAuditTaskID());
        if(count<1){
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.INSERT_FAILE,null,null,0,0);
        }
        return NR.r();
    }

    @Override
    public String updateHseAuditTask(HseAuditTaskPojo hseAuditTaskPojo) {
        int count = hseDao.updateHseAuditTask(hseAuditTaskPojo);
        if(count<1){
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.UPDATE_FAILE,null,null,0,0);
        }
        return NR.r();
    }

    @Override
    public String deleteHseAuditTask(Integer auditTaskID) {
        System.out.println(auditTaskID);
        HseAuditTaskPojo pojo = hseDao.queryHseAuditTaskByID(auditTaskID);
        System.out.println(pojo);
        if(pojo==null){
            return NR.r(CodeDict.DELETE_FAILE,"删除失败，该任务不存在");
        }

        if(pojo.getStatus().equals("完成")){
            return NR.r(CodeDict.DELETE_FAILE,"该任务已完成");
        }


        hseDao.deleteHseAuditTask(auditTaskID);
        hseDao.deleteHSEAuditGroupByTaskID(auditTaskID);

        List<Integer> groupIDs = hseDao.getGroupIDByTaskID(auditTaskID);
        for (Integer id:groupIDs){
            hseDao.deleteMemberByGroupID(id);
        }


        return NR.r();
    }

    @Override
    @Transactional
    public String addHseAuditGroupMembers(HseAuditGroupMembersDto hseAuditGroupMembersDto) {
        List<HseAuditGroupMemberDto> members = hseAuditGroupMembersDto.getMembers();
        for (HseAuditGroupMemberDto member : members) {
            hseDao.addHseAuditGroupMember(member);
        }

        return NR.r();
    }

    @Override
    @Transactional
    public String updateHseAuditGroupMembers(HseAuditGroupMembersDtos hseAuditGroupMembersDto) {
        List<HseAuditGroupMemberDtos> members = hseAuditGroupMembersDto.getMembers();
        Integer groupID = members.get(0).getAuditGroupID();
        //修改检查人员
        if(members!=null&&members.size()>0){
            hseDao.dropHseAuditGroupMember(groupID);
            for (HseAuditGroupMemberDtos member : members) {
                hseDao.addHseAuditGroupMembers(member);
            }
        }
        //修改检查区域
        String companyNames = hseAuditGroupMembersDto.getCompanyNames();
        if(!"".equals(companyNames)&&companyNames!=null){
            String[] codes = companyNames.split(",");
            StringBuilder companyCodes=new StringBuilder();
            for (String code : codes) {
                companyCodes.append(companyDao.queryByCompanyName(code)).append(",");
            }
            companyCodes.deleteCharAt(companyCodes.length()-1);
            hseDao.updateHseAuditGroupAreas(companyCodes.toString(),companyNames,groupID);
        }
        return NR.r();
    }

    @Override
    @Transactional
    public String updateHseAuditGroupMembersTopics(HseAuditGroupMembersDto hseAuditGroupMembersDto) {
        List<HseAuditGroupMemberDto> members = hseAuditGroupMembersDto.getMembers();
        for (HseAuditGroupMemberDto member : members) {
            hseDao.updateHseAuditGroupMembersTopics(member);
        }
        return NR.r();
    }

    @Override
    public R queryHseAuditTopic(HseAuditSystem hseAuditSystem) {
        List<HseAuditSystem>list=new ArrayList<>();
        String[] arr=hseAuditSystem.getType().split(",");
        for (String type:arr) {
            hseAuditSystem.setType(type);
            list.addAll(hseDao.queryHseAuditTopic(hseAuditSystem));
        }
        //遍历插入：质量|Evalueitem
        for (HseAuditSystem pojo:list) {
            pojo.setEvalueItem(pojo.getType()+"|"+pojo.getEvalueItem());
        }
        return R.ok().put("data",list);
    }

    @Override
    public String queryHseAuditSystemCheckItems(String code) {
        return NR.r(hseDao.queryHseAuditSystemCheckItems(code));
    }

    @Override
    public String queryHseAuditSystemByCode(String code,String status) {
        List<HseAuditSystem> list = hseDao.queryHseAuditSystemByCode(code);
        QhseeSystemDto qhseeSystemDto=new QhseeSystemDto();//插入QhseeSystemDto进入
        qhseeSystemDto=hseDao.queryQhseeSystemDto(code);
        List<Integer> codes = new ArrayList<>();
        Map<String,HseAuditSystem> map= new TreeMap<>();
        for (HseAuditSystem hseAuditSystem : list) {
            String hseCode = hseAuditSystem.getHseAuditSystemCode();
            hseAuditSystem.setQHSEESystemID(qhseeSystemDto.getQHSEESystemID());//插入进结果
            hseAuditSystem.setQHSEESystemCode(qhseeSystemDto.getQHSEESystemCode());
            hseAuditSystem.setQHSEESystemItem(qhseeSystemDto.getQHSEESystemItem());
            if("质量审核".equals(status)) hseAuditSystem.setAllSystem(qhseeSystemDto.getQualitySystem());
            else if("HSE审核".equals(status)) hseAuditSystem.setAllSystem(qhseeSystemDto.getHSESystem());
            map.put(hseCode,hseAuditSystem);
            if(codes.indexOf(hseCode.length())==-1){
                codes.add(hseCode.length());
            }
        }

        Collections.sort(codes);
        List<HseAuditSystem> result = new ArrayList<>();
        for (Map.Entry<String, HseAuditSystem> entry : map.entrySet()) {
            String hseCode = entry.getKey();
            HseAuditSystem hseAuditSystem = entry.getValue();
            if(hseCode.length()==code.length()){//根节点
                result.add(hseAuditSystem);
            }else{
                String parentCode = hseCode.substring(0, codes.get(codes.indexOf(hseCode.length()) - 1));
                HseAuditSystem parentHseAuditSystem = map.get(parentCode);
                if(parentHseAuditSystem.getChildren()==null){
                    LinkedList<HseAuditSystem> children = new LinkedList<>();
                    children.add(hseAuditSystem);
                    parentHseAuditSystem.setChildren(children);
                }else{
                    parentHseAuditSystem.getChildren().add(hseAuditSystem);
                }
            }
        }
        return NR.r(result);
    }

    @Override
    public String queryTaskAndGroupByStaffID(String staffID,String round,String taskDate) {
        List<HseTaskAndGroupDto> hseTaskAndGroupDtos = hseDao.queryTaskAndGroupByStaffID(staffID,round,taskDate);
//      查询组长信息
        for (HseTaskAndGroupDto hseTaskAndGroupDto : hseTaskAndGroupDtos) {
            HseTaskAndGroupDto groupLeader = hseDao.queryGroupLeader(hseTaskAndGroupDto.getAuditGroupID());
            if(groupLeader!=null){
                hseTaskAndGroupDto.setGroupLeaderID(groupLeader.getGroupLeaderID());
                hseTaskAndGroupDto.setGroupLeaderName(groupLeader.getGroupLeaderName());
            }
        }
        return NR.r(hseTaskAndGroupDtos);
    }

    @Override
    public String queryAuditSubjectRecord(QHSEECheckRecord qhseeCheckRecord) {
        List<QHSEECheckRecord> list=new ArrayList<>();
        list=hseDao.queryAuditSubjectRecord(qhseeCheckRecord);
        return NR.r(list);
    }

    @Override
    public String queryAuditSubjectRecordByStatus(HseCheckRecordDto hseCheckRecordDto) {
        List<QHSEECheckRecord> list=new ArrayList<>();
        PageHelper.startPage(hseCheckRecordDto.getNum(),hseCheckRecordDto.getSize());
        if (hseCheckRecordDto.getStartDate()==null||hseCheckRecordDto.getStartDate().equals("")){
            hseCheckRecordDto.setStartDate("2000-01-01");
        }
        if (hseCheckRecordDto.getEndDate()==null||"".equals(hseCheckRecordDto.getEndDate())){
            hseCheckRecordDto.setEndDate("3000-01-01");
        }
        list=hseDao.queryAuditSubjectRecordByStatus(hseCheckRecordDto);
        PageInfo<QHSEECheckRecord> page=new PageInfo<>(list);
        return NR.r(list,Integer.parseInt(String.valueOf(page.getTotal())),hseCheckRecordDto.getNum());
    }

    @Override
    public String addCheckRecord(QHSEECheckRecord qhseeCheckRecord) {
        String companyCode = qhseeCheckRecord.getCompanyCode();
        if(companyCode.length()==2){
            String parentCompanyName = companyDao.queryByCompanyCode(companyCode);
            qhseeCheckRecord.setParentCompanyName(parentCompanyName);
        }
        if(companyCode.length()==4){
            String parentCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 4));
            qhseeCheckRecord.setParentCompanyName(parentCompanyName);
        }

        if(companyCode.length()>=6 && (companyCode.length()<=8)){
            String parentCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 4));
            String baseCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 6));
            qhseeCheckRecord.setBasicCompanyName(baseCompanyName);
            qhseeCheckRecord.setParentCompanyName(parentCompanyName);
        }

        if (companyCode.length()>=10){
            String parentCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 4));
            String baseCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 6));
            String companyName = companyDao.queryByCompanyCode(companyCode);
            qhseeCheckRecord.setOperationTeamName(companyName);
            qhseeCheckRecord.setBasicCompanyName(baseCompanyName);
            qhseeCheckRecord.setParentCompanyName(parentCompanyName);
        }
        qhseeCheckRecord.setStatus("暂存");
        hseDao.addCheckRecord(qhseeCheckRecord);
        return NR.r();
    }

    @Override
    public String updateCheckRecord(QHSEECheckRecords qhseeCheckRecord) {
        String companyCode = qhseeCheckRecord.getCompanyCode();
        System.out.println(companyCode);
        if(companyCode.length()>=4){
            String parentCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 4));
            qhseeCheckRecord.setParentCompanyName(parentCompanyName);
        }

        if(companyCode.length()>=6){
            String baseCompanyName = companyDao.queryByCompanyCode(companyCode.substring(0, 6));
            qhseeCheckRecord.setBasicCompanyName(baseCompanyName);
        }
        String companyName = companyDao.queryByCompanyCode(companyCode);
        qhseeCheckRecord.setCompanyName(companyName);
        hseDao.updateCheckRecord(qhseeCheckRecord);
        return NR.r();
    }

    @Override
    public String updateCheckRecordStatus(String ids) {
        String[] ss=ids.split(",");
        for (String s:ss) {
            hseDao.updateCheckRecordStatus(s);
        }
        return NR.r();
    }

    @Override
    public R queryQhseeCheckRecord(QHSEECheckRecords qhseeCheckRecord) {
        List<QHSEECheckRecords> qhseeCheckRecords = hseDao.queryQhseeCheckRecord(qhseeCheckRecord);
        return R.ok().put("data",qhseeCheckRecords);
    }

    @Override
    public String updateQhseeCheckRecordStatus(QHSEECheckRecord qhseeCheckRecord) {
        hseDao.updateQhseeCheckRecordStatus(qhseeCheckRecord.getRecordStatus(),qhseeCheckRecord.getQhseeCheckRecordID());
        return NR.r();
    }

    @Override
    @Transactional
    public String deleteQHSEECheckRecord(List<String> QHSEECheckRecordList) {
        //test
        hseDao.delectRectRecordByCheckRecordID(QHSEECheckRecordList);
        hseDao.deleteQHSEECheckRecord(QHSEECheckRecordList);
        return NR.r();

    }

    @Override
    public R queryQHSEECheckRecordNums(QHseeCheckRecordDto qhseeCheckRecord) {
        HashSet<String> hs1=new HashSet<>();//暂存子节点以及父节点
        HashSet<String> hs=new HashSet<>();
        if (qhseeCheckRecord.getStartDate()==null||qhseeCheckRecord.getStartDate().equals("")){
            qhseeCheckRecord.setStartDate("2000-01-01");
        }
        if (qhseeCheckRecord.getEndDate()==null||"".equals(qhseeCheckRecord.getEndDate())){
            qhseeCheckRecord.setEndDate("3000-01-01");
        }
        //先查询所有子节点
            String [] code=qhseeCheckRecord.getCompanyCode().split(",");
                for (String codes:code) {
                    qhseeCheckRecord.setCompanyCode(codes);
                    hs1.addAll(hseDao.queryChidrenNode(qhseeCheckRecord));
                }


        //遍历查询父节点
        if(!hs1.isEmpty()){
            for (String str:hs1) {
                str=str.substring(0,2);
                hs.addAll(hseDao.queryParentNode(str));
            }
        }
        hs.addAll(hs1);
        List<QHSEECheckRecordNumsDto>list=new ArrayList<>();

        //遍历查询数量
        if(!hs.isEmpty()){
            System.out.println(qhseeCheckRecord.getCompanyCode());
            System.out.println(code.length);
            for (String str:hs) {
                List<QHSEECompanyDto> company =new ArrayList<>();
                QHSEECheckRecordNumsDto qHSEECheckRecordNumsDto=new QHSEECheckRecordNumsDto();;//暂存
                int num=0;//全局num
                qHSEECheckRecordNumsDto.setCode(str);
                qHSEECheckRecordNumsDto.setSubject(hseDao.querySubject(str));//查询主题
                if(code.length!=0 &&str.length()==4){//判空
                    for (String codes:code) {
                        QHSEECompanyDto qHSEECompanyDto=new QHSEECompanyDto();
                        qHSEECompanyDto.setName(companyDao.queryByCompanyCode(codes));
                        System.out.println(qHSEECompanyDto.getName());
                        qhseeCheckRecord.setCompanyCode(codes);
                        Integer  numIndex=hseDao.queryCompanyNum(str,qhseeCheckRecord);
                        qHSEECompanyDto.setValue(numIndex);
                        num+=numIndex;
                        company.add(qHSEECompanyDto);
                    }

                }else if(code.length!=0 &&str.length()==2){
                    for (String codes:code) {
                        QHSEECompanyDto qHSEECompanyDto=new QHSEECompanyDto();
                        qHSEECompanyDto.setName(companyDao.queryByCompanyCode(codes));
                        qhseeCheckRecord.setCompanyCode(codes);
                        Integer  numIndex=hseDao.queryNums(str,qhseeCheckRecord);
                        qHSEECompanyDto.setValue(numIndex);
                        num+=numIndex;
                        company.add(qHSEECompanyDto);
                    }
                }
                qHSEECheckRecordNumsDto.setNum(num);//共同属性抽取
                qHSEECheckRecordNumsDto.setCompany(company);
                list.add(qHSEECheckRecordNumsDto);
            }
        }

        R ok = R.ok();
        ok.put("data", treeUtil.getCurrentQhseElementTree1(list));
        return ok;
    }

    @Override
    public R cascadingQuery(String year, String round, String auditGroupName) {
        return R.ok().put("data",companyDao.QueryByAll(year,round,auditGroupName));
    }
}